package cn.bdqn.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author 梁非凡
 * @date 2018/7/31 16:52
 */
public class Baseutils {
    //是一个map  k是当前线程 v是conn所以只有一个T
    private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
    private static ComboPooledDataSource ds=null;
    static {
        try {
            ds=new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql:///dom");
            ds.setUser("root");
            ds.setPassword("123456");
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }
public static QueryRunner getQueryRunner(){
    QueryRunner runner = new QueryRunner(ds);
    return runner;
}
public static Connection getconn(){
    Connection conn = threadLocal.get();
    if (conn==null) {
        try {
            conn = ds.getConnection();
            threadLocal.set(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return conn;
}

    public static void begin() throws Exception {
        Connection conn = Baseutils.getconn();
        conn.setAutoCommit(false);
    }
    public static  void  rollback() throws Exception {
        Connection conn = Baseutils.getconn();
        conn.rollback();
    }
    public static void comm() throws Exception {
        Connection conn = Baseutils.getconn();
        conn.commit();
        //关闭资源
        conn.close();
        //清空threadlocal中的conn
        threadLocal.set(null);
    }
}
